package validators;

import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputSecret;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import rullekake.beans.util.LocaleHelper;

/**
 *
 * Sjekker at passordet i feltet som valideres er likt passordet i feltet "password"
 *
 */

@FacesValidator("passwordEqualsValidator")
public class PasswordEqualsValidator implements Validator {

    public PasswordEqualsValidator() {
    }

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        HtmlInputSecret secondInput = (HtmlInputSecret) component;
        HtmlInputSecret firstInput = (HtmlInputSecret) secondInput.findComponent("password");
        final String secondVal = value.toString(),
                     firstVal = firstInput.getLocalValue().toString();

        final boolean matchesConfirmation = secondVal.equals(firstVal);

        if (!matchesConfirmation) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    ResourceBundle.getBundle(LocaleHelper.getBundleName()).getString("error_passwordsNotEqual"),
                    ResourceBundle.getBundle(LocaleHelper.getBundleName()).getString("error_passwordsNotEqual")));
        }
    }
}